package handler

import (
	"callsips/internal/fscurl/xmlcurl"
	"callsips/internal/logic"
	"callsips/internal/svc"
	"callsips/internal/types"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
)

func FreeswitchHander(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var Header = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>` + "\n"
		var response []byte = xmlcurl.NotFound(make(map[string]string))
		if err := r.ParseForm(); err != nil {
			logx.Errorf("解析ParseForm信息错误:%s", err.Error())
			w.Header().Set("Content-Type", "application/xml")
			w.Write(append([]byte(Header), response...))
			return
		}

		form := make(map[string]string)
		for key := range r.PostForm {
			form[key] = r.PostFormValue(key)
		}

		l := logic.NewCallsipsLogic(r.Context(), svcCtx)
		resp, err := l.FsCurl(form)
		logx.Info(string(resp))
		if err != nil {
			logx.Errorf("获取信息错误:%s", err.Error())
			w.Header().Set("Content-Type", "application/xml")
			w.Write(append([]byte(Header), response...))
			return
		}

		w.Header().Set("Content-Type", "application/xml")
		w.Write(append([]byte(Header), resp...))
	}
}

// 话单推送
func FsRecordHander(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			w.Write([]byte("fail"))
			return
		}

		var cdr string = r.PostFormValue("cdr")

		if cdr == "" {
			w.Write([]byte("fail"))
		}
		var req types.FsRecordReq

		if errs := json.Unmarshal([]byte(cdr), &req); errs != nil {
			//logx.Info(errs)
			w.Write([]byte("fail"))
		}

		l := logic.NewFsrecordLogic(r.Context(), svcCtx)
		if err := l.Record(&req); err != nil {
			logx.Infof("话单入库错误信息为:%s", err.Error())
			w.Write([]byte("fail"))
		}

		w.Write([]byte("ok"))
	}
}
